<?php
// +----------------------------------------------------------------------
// | Niucloud-admin 企业快速开发的多应用管理平台
// +----------------------------------------------------------------------
// | 官方网址：https://www.niucloud.com
// +----------------------------------------------------------------------
// | niucloud团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: Niucloud Team
// +----------------------------------------------------------------------

namespace app\api\service\cart;


use app\api\model\card\Card;
use app\api\model\card\CardSku;
use app\service\core\cart\CoreCartService;
use app\api\model\cart\Cart;
use app\core\base\BaseApiService;

/**
 * 购物车服务层
 * Class CartService
 */
class CartService extends BaseApiService
{

     public function __construct()
     {
          parent::__construct();
          $this->model = new Cart();
     }

     /**
      * 添加购物车
      * @param $data
      * @return mixed
      */
     public function add($data)
     {
          $data['member_id'] = $this->member_id;
          $info = $this->model->where([
               ['member_id', '=', $data['member_id']],
               ['product_id', '=', $data['product_id']],
               ['sku_id', '=', $data['sku_id']],
          ])->field('id,num')->findOrEmpty()->toArray();

          if (!empty($info)) {
               // 存在，更新数量
               $update = [
                    'num' => $info['num'] + $data['num']
               ];
               $this->model->where([['id', '=', $info['id']]])->update($update);
               return $info['id'];
          } else {
               // 添加
               // product_id跟sku_id 是否对应
               $product_info = CardSku::where([
                    ['id', '=', $data['sku_id']],
                    ['product_id', '=', $data['product_id']],
               ])->findOrEmpty()->toArray();
               if (!empty($product_info)) {
                    $res = $this->model->create($data);
                    return $res->id;
               }
               return 0;

          }
     }

     /**
      * 编辑购物车数量
      * @param $data
      * @return bool
      */
     public function edit($data)
     {
          $data['member_id'] = $this->member_id;
          $info = $this->model->where([
               ['id', '=', $data['id']],
               ['member_id', '=', $data['member_id']],
          ])->field('sku_id')->findOrEmpty()->toArray();

          if (empty($info)) return false;

          $update = [
               'num' => $data['num']
          ];

          if (!empty($data['sku_id']) && $info['sku_id'] != $data['sku_id']) {
               $update['sku_id'] = $data['sku_id'];

               $cart_info = $this->model->where([
                    ['sku_id', '=', $data['sku_id']],
                    ['member_id', '=', $this->member_id],
               ])->field('id')->findOrEmpty()->toArray();

               if (!empty($cart_info)) {
                    $this->model->where([['id', '=', $cart_info['id']]])->delete();
               }
          }

          $this->model->where([['id', '=', $data['id']]])->update($update);
          return true;
     }

     /**
      * 购物车删除，支持批量
      * @param $data
      * @return bool
      */
     public function del($data)
     {
          $this->model->where([['member_id', '=', $this->member_id], ['id', 'in', $data['ids']]])->delete();
          return true;
     }

     /**
      * 清空购物车
      * @return bool
      */
     public function clear()
     {
          $this->model->where([['member_id', '=', $this->member_id]])->delete();
          return true;
     }

     /**
      * 获取购物车列表
      * @param $data
      * @return array
      */
     public function getList($data)
     {

          $data['member_id'] = 6;
          $field = 'id, member_id, product_id, sku_id, num, market_type, market_type_id, status, invalid_remark';
          $order = "create_time desc";
          $list = $this->model->withSearch(["member_id"], $data)->field($field)
               ->with(['cardSku', 'card'])->order($order)->select()->toArray();
          //计算购物车商品总数
          $total_num = 0;
          $total_price = 0;

          foreach ($list as &$v) {
               $tags = explode(',', $v['tags']);
               if (count($tags) < 2) {
                    $v['tags'] = $tags;
               } else {
                    if ($tags['1'] == '咒术回战') {
                         $tags['1'] = 'https://kaduoduo-1325965390.cos-website.ap-guangzhou.myqcloud.com/upload/attachment/image/202406/01/1717225797fe95405876a9eae4cb9dadddb63ecd17_tencent.png';
                    } elseif ($tags['1'] == '航海王') {
                         $tags['1'] = 'https://kaduoduo-1325965390.cos-website.ap-guangzhou.myqcloud.com/upload/attachment/image/202406/01/17172258119c8d04c99fc945c50473c86abf9d45e4_tencent.png';
                    } elseif ($tags['1'] == '宝可梦') {
                         $tags['1'] = 'https://kaduoduo-1325965390.cos-website.ap-guangzhou.myqcloud.com/upload/attachment/image/202406/01/1717225805b035a7e2401eeabd9a876953dbbb1b1f_tencent.png';
                    } elseif ($tags['1'] == '七龙珠') {
                         $tags['1'] = 'https://kaduoduo-1325965390.cos-website.ap-guangzhou.myqcloud.com/upload/attachment/image/202406/01/17172258141936ff366fac47e4eaf662b4765d373a_tencent.png';
                    } elseif ($tags['1'] == '游戏王') {
                         $tags['1'] = 'https://kaduoduo-1325965390.cos-website.ap-guangzhou.myqcloud.com/upload/attachment/image/202406/01/171722581701706ca22ec37e617417dabf4b73cfa7_tencent.png';
                    }
               }
               if(empty($v)){
                    continue;
               }
               $total_num += $v['num']??'0';
               $total_price += $v['num'] * $v['cardSku']['money_price']??"0";
          }
          return ['list'=>$list,'count'=>$total_num,'money'=>$total_price];
     }

     /**
      * 获取购物车商品列表
      * @param $data
      * @return array
      */
     public function getGoodsList($data)
     {
          $data['member_id'] = $this->member_id;
          $field = 'id, member_id, goods_id, sku_id, num, market_type, market_type_id, status, invalid_remark';
          $order = "create_time desc";
          return $this->model->withSearch(["member_id"], $data)->field($field)
               ->with([
                    'goods' => function ($query) {
                         $query->withField('goods_id, goods_name, goods_type, sub_title, goods_cover, unit, stock, sale_num + virtual_sale_num as sale_num, status,delete_time');
                    },
                    'goodsSku' => function ($query) {
                         $query->withField('sku_id, sku_name, sku_image, sku_no, goods_id, sku_spec_format, price, market_price, sale_price, stock, weight, volume, is_default');
                    },
                    // 商品规格项/规格值列表
                    'goodsSpec' => function ($query) {
                         $query->field('spec_id, goods_id, spec_name, spec_values');
                    },
               ])->order($order)->paginate($data['limit'])->toArray();

          return (new CoreCartService())->getGoodsList($data);
     }

     /**
      * 获取购物车数量
      * @param $data
      * @return float
      */
     public function getSum($data)
     {
          $condition = [
               ['member_id', '=', $this->member_id]
          ];
          if (!empty($data['goods_id'])) {
               $condition[] = ['goods_id', '=', $data['goods_id']];
          }
          return $this->model->where($condition)->sum('num');
     }

}
